-- select * from FN_CALCULATE_CALENDAR_MONTH ('12/23/2008', 3)

ALTER FUNCTION FN_CALCULATE_CALENDAR_MONTH ( @DATE_TO_FIND DATETIME, @MONTHS_TO_ADD INT )
RETURNS @RESULTS TABLE ( MONTH_START_DATE datetime, MONTH_END_DATE datetime  )
AS
BEGIN
	DECLARE @QTR_START_DATE DATETIME
	DECLARE @MONTH_START_DATE DATETIME
	DECLARE @MONTH_END_DATE DATETIME
	DECLARE @INDEX INT
	DECLARE @MONTH_INDEX INT
	IF ( @DATE_TO_FIND IS NOT NULL AND LTRIM(RTRIM(@DATE_TO_FIND)) != '' )
	BEGIN
		SELECT @QTR_START_DATE = CQC_START_DATE FROM Company_Quarterly_Calendar WHERE @DATE_TO_FIND >= CQC_START_DATE AND @DATE_TO_FIND <= CQC_END_DATE 
		IF ( @DATE_TO_FIND >= @QTR_START_DATE AND @DATE_TO_FIND < DATEADD(WW, 4, @QTR_START_DATE)  )
		BEGIN
			SET @MONTH_START_DATE = @QTR_START_DATE
			SET @MONTH_END_DATE = DATEADD(WW, 4, @QTR_START_DATE)
			SET @INDEX = 1
		END
		ELSE IF(  @DATE_TO_FIND >= DATEADD(WW, 4, @QTR_START_DATE) AND @DATE_TO_FIND < DATEADD(WW, 8, @QTR_START_DATE) )
		BEGIN		
			SET @MONTH_START_DATE = DATEADD(WW, 4, @QTR_START_DATE)
			SET @MONTH_END_DATE = DATEADD(WW, 8, @QTR_START_DATE)
			SET @INDEX = 2
		END
		ELSE
		BEGIN
			SET @MONTH_START_DATE = DATEADD(WW, 8, @QTR_START_DATE)
			SET @MONTH_END_DATE = DATEADD(WW, 13, @QTR_START_DATE)
			SET @INDEX = 3
		END

		IF @MONTHS_TO_ADD > 0
		BEGIN
			SET @MONTH_INDEX = 0
			WHILE @MONTH_INDEX < @MONTHS_TO_ADD
			BEGIN
				IF @INDEX = 2
				BEGIN
					SET @MONTH_START_DATE = @MONTH_END_DATE
					SET @MONTH_END_DATE = DATEADD(WW, 5, @MONTH_START_DATE)
					SET @INDEX = 3
				END
				ELSE 
				BEGIN
					SET @MONTH_START_DATE = @MONTH_END_DATE
					SET @MONTH_END_DATE = DATEADD(WW, 4, @MONTH_START_DATE)
					IF @INDEX = 1
						SET @INDEX = 2
					ELSE
						SET @INDEX = 1
				END
				SET @MONTH_INDEX = @MONTH_INDEX +1			
			END
		END
	END
	INSERT INTO @RESULTS VALUES( @MONTH_START_DATE, DATEADD( ss, -1, @MONTH_END_DATE ) )
	RETURN
END
